package com.hfjyz.expert.expert.action;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.ServletActionContext;

import com.hfjyz.base.constant.BaseConstant;
import com.hfjyz.base.exception.BaseException;
import com.hfjyz.expert.expert.bean.ExpertBean;
import com.hfjyz.expert.expert.bean.ExpertExcelBean;
import com.hfjyz.expert.expert.bean.ExpertSearchBean;

public class ExpertExcelAction extends ExpertAction {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -2990707684979140324L;
    private static final Log SYS_LOG = LogFactory.getLog(BaseConstant.SYS_LOG);

    public static final String XML_EXPERT_TEMPLATE = "expertTemplate.xml";
    public static final String PROP_EXPERT_TEMPLATE = "expertTemplate.properties";
    public static final String XLS_EXPERT_TEMPLATE = "expertTemplate.xls";
    public static final String XLS_EXPERT_LIST_TEMPLATE = "expertListTemplate.xls";
    public static final String XLS_EXPERT_INPUT_TEMPLATE = "expert.xls";
    public static final String DOC_EXPERT_INPUT_TEMPLATE = "expert.doc";

    // upload params
    private File expertExcel = null;
    private String expertExcelFileName = null;
    private String expertExcelFileContentType = null;
    private ExpertBean excelExpert = null;

    // download params
    private String downloadFileName = null;
    private InputStream excelStream = null;
    private String type = null;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public File getExpertExcel() {
        return expertExcel;
    }

    public void setExpertExcel(File expertExcel) {
        this.expertExcel = expertExcel;
    }

    public String getExpertExcelFileName() {
        return expertExcelFileName;
    }

    public void setExpertExcelFileName(String fileFileName) {
        this.expertExcelFileName = fileFileName;
    }

    public String getExpertExcelFileContentType() {
        return expertExcelFileContentType;
    }

    public void setExpertExcelFileContentType(String fileFileContentType) {
        this.expertExcelFileContentType = fileFileContentType;
    }

    public ExpertBean getExcelExpert() {
        return excelExpert;
    }

    public void setExcelExpert(ExpertBean excelExpert) {
        this.excelExpert = excelExpert;
    }

    public String importExcel() throws BaseException {
        if (expertExcelFileName.endsWith(".xls")) {
            importXLS();
        } else if (expertExcelFileName.endsWith(".doc")) {
            importDOC();
        } else {
            throw new BaseException("专家信息导入失败！专家信息导入文件格式不正确，请下载使用正确模版！");
        }
        return SUCCESS;
    }
    
    private void importXLS() throws BaseException {
        map = new HashMap<String, Object>();
        try {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/");
            String path = rootPath + "WEB-INF\\conf\\expert\\" + XML_EXPERT_TEMPLATE;

            getService().importExpertXLS(path, expertExcel, excelExpert.getCategoryId(), excelExpert.getRemark());
        } catch (BaseException e) {
            map.put("errorMsg", e.getMessage());
        } catch (Exception e) {
            SYS_LOG.error("发生未知错误！", e);
            map.put("errorMsg", "发生未知错误，请联系管理员！");
        }
    }
    
    private void importDOC() throws BaseException {
        map = new HashMap<String, Object>();
        try {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/");
            String path = rootPath + "WEB-INF\\conf\\expert\\" + PROP_EXPERT_TEMPLATE;

            getService().importExpertDOC(path, expertExcel, excelExpert.getCategoryId(), excelExpert.getRemark());
        } catch (BaseException e) {
            map.put("errorMsg", e.getMessage());
        } catch (Exception e) {
            SYS_LOG.error("发生未知错误！", e);
            map.put("errorMsg", "发生未知错误，请联系管理员！");
        }
    }

    public String getDownloadFileName() {
        return downloadFileName;
    }

    public void setDownloadFileName(String downloadFileName) {
        this.downloadFileName = downloadFileName;
    }

    public InputStream getExcelStream() {
        return excelStream;
    }

    public void setExcelStream(InputStream excelStream) {
        this.excelStream = excelStream;
    }

    public String exportExcel() throws BaseException {
        ByteArrayOutputStream baos = null;
        try {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/");
            String templatePathSingle = rootPath + "WEB-INF\\conf\\expert\\" + XLS_EXPERT_TEMPLATE;
            String templatePathMulti = rootPath + "WEB-INF\\conf\\expert\\" + XLS_EXPERT_LIST_TEMPLATE;

            HttpSession session = ServletActionContext.getRequest().getSession();
            Object o = session.getAttribute(BaseConstant.SESSION_CONDITION_KEY);
            ExpertSearchBean searchBean = null;
            if (o instanceof ExpertSearchBean) {
                searchBean = (ExpertSearchBean) o;
            }
            if (searchBean == null) {
                searchBean = expertSearch;
            }
            List<ExpertBean> expertList = getService().findExpertWithoutPage(getSearchCondition(),
                    searchBean);
            List<ExpertExcelBean> excelList = getExcelBeanList(expertList);

            Workbook wb = null;
            if (excelList.size() == 1) {
                wb = getService().exportExpert(templatePathSingle, excelList);
            } else {
                wb = getService().exportExpert(templatePathMulti, excelList);
            }
            baos = new ByteArrayOutputStream();
            wb.write(baos);
            baos.flush();
            byte[] excelBytes = baos.toByteArray();
            excelStream = new ByteArrayInputStream(excelBytes, 0, excelBytes.length);

            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            downloadFileName = "专家信息详细_" + sf.format(new Date()) + ".xls";
            downloadFileName = new String(downloadFileName.getBytes(), "ISO8859-1");
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("导出Excel失败！", e);
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
            }
        }
        return SUCCESS;
    }

    public String exportDetail() throws BaseException {
        ByteArrayOutputStream baos = null;
        try {
            String rootPath = ServletActionContext.getServletContext().getRealPath("/");
            String templatePathSingle = rootPath + "WEB-INF\\conf\\expert\\" + XLS_EXPERT_TEMPLATE;

            Integer id = Integer.valueOf(getSelectIds());
            ExpertBean expert = getService().updateInitExpert(id);
            List<ExpertBean> expertList = new ArrayList<ExpertBean>();
            expertList.add(expert);
            List<ExpertExcelBean> excelList = getExcelBeanList(expertList);
            Workbook wb = getService().exportExpert(templatePathSingle, excelList);
            baos = new ByteArrayOutputStream();
            wb.write(baos);
            baos.flush();
            byte[] excelBytes = baos.toByteArray();
            excelStream = new ByteArrayInputStream(excelBytes, 0, excelBytes.length);

            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            downloadFileName = "专家信息详细_" + sf.format(new Date()) + ".xls";
            downloadFileName = new String(downloadFileName.getBytes(), "ISO8859-1");
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("导出Excel失败！", e);
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
            }
        }

        return SUCCESS;
    }
    
    public String downloadTemplate() throws BaseException {
        String rootPath = ServletActionContext.getServletContext().getRealPath("/");
        String templatePath = null;
        if ("word".equals(type)) {
            downloadFileName = "专家信息详细模板.doc";
            templatePath = rootPath + "WEB-INF\\conf\\expert\\" + DOC_EXPERT_INPUT_TEMPLATE;
        } else {
            downloadFileName = "专家信息详细模板.xls";
            templatePath = rootPath + "WEB-INF\\conf\\expert\\" + XLS_EXPERT_INPUT_TEMPLATE;
        }
        try {
            downloadFileName = new String(downloadFileName.getBytes(), "ISO8859-1");
            excelStream = new FileInputStream(templatePath);
        } catch (Exception e) {
            throw new BaseException("模板下载失败！", e);
        }
        return SUCCESS;
    }
    
    private List<ExpertExcelBean> getExcelBeanList(List<ExpertBean> expertList) {
        List<ExpertExcelBean> beanList = new ArrayList<ExpertExcelBean>();
        if (expertList == null || expertList.isEmpty()) {
            return beanList;
        }
        
        for (ExpertBean expert : expertList) {
            beanList.add(new ExpertExcelBean(expert));
        }
        return beanList;
    }
}
